package com.weaver.seconddev.api.tl.purchase_api;

/**
 * E9原始类路径:com.api.tl.purchase_api.CreatePurchaseOrderNPRAction
 * JAVA替换说明文档:https://ncnb71xwgeda.feishu.cn/wiki/JLsjwxK8xiHuPIkdu0Dc27Rlnaf?from=from_copylink
 */

import com.weaver.common.distribution.genid.IdGenerator;
import com.weaver.seconddev.api.tl.service.SAPCommonService;
import com.weaver.seconddev.api.tl.service.DictCommonService;
import org.apache.commons.lang3.StringUtils;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.verupgrade.conn.CONN_TYPE;
import java.lang.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import com.weaver.verupgrade.workflow.request.RequestManager;
import com.weaver.esb.api.rpc.EsbServerlessRpcRemoteInterface;
import com.weaver.common.base.entity.result.WeaResult;
import org.springframework.beans.factory.annotation.Autowired;
import com.weaver.verupgrade.soa.workflow.request.RequestInfo;
import java.util.HashMap;
import com.weaver.verupgrade.conn.RecordSet;
import com.weaver.verupgrade.general.BaseBean;
import com.weaver.verupgrade.general.Util;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

import javax.annotation.Resource;

/**
 * 创建PurchaseOrder统一接口
 */
@org.springframework.stereotype.Service("tl_purchase_api_CreatePurchaseOrderNPRAction")
public class CreatePurchaseOrderNPRAction implements Action, EsbServerlessRpcRemoteInterface {

    // 对应E9的请求信息对象
    @Autowired
    private RequestInfo requestInfoTemp;

    public static final org.slf4j.Logger logger_52c94c32 = LoggerFactory.getLogger(CreatePurchaseOrderNPRAction.class);


    @Resource(name = "tl_service_SAPCommonService")
    private SAPCommonService sapCommonService;

    @Override
    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        Map<String, Object> weaverResultMap = new HashMap<>();
        Long requestIdTemp = Long.parseLong(String.valueOf(requestInfoMap.getOrDefault("requestid", -1)));
        Long userIdTemp = Long.parseLong(String.valueOf(requestInfoMap.getOrDefault("userid", -1)));
        RequestInfo requestInfo = requestInfoTemp.getRequestInfo(requestIdTemp, userIdTemp);
        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
        /* 获取requestId
 TODO 返回值:requestId 存在类型转换风险 e9类型:java.lang.String e9真实类型: int  e10类型:java.lang.String e10真实类型: long */
        String requestId = requestInfo.getRequestid();
        /* 获取创建人ID
 TODO 返回值:createdId 类型发生变化 e9类型:int  e10类型:Long*/
        long createdId = requestInfo.getRequestManager().getUserId();
        /* 获取流程ID
 TODO 返回值:workflowId 存在类型转换风险 e9类型:java.lang.String e9真实类型: int  e10类型:java.lang.String e10真实类型: long */
        String workflowId = requestInfo.getWorkflowid();
        logger_52c94c32.info(String.valueOf("RequestId:" + requestId + "======Start Create NPR PO======WorkflowId:" + workflowId + ",CreatedId:" + createdId));
        // 获取PO创建人networkId
        String networkId = null;
        //todo
       //String queryNetworkIdSql = "select field15 from cus_fielddata where id = ? and scopeid = -1";
        String queryNetworkIdSql = "select field15,eteams.employee.id from  eteams.hrmemployeedefined left join   eteams.employee  ON  eteams.hrmemployeedefined.form_data_id = eteams.employee.formdata\n" +
                "where eteams.employee.id= ? ";
        String poolname = CONN_TYPE.workflow.getType();
        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
        rs.executeQuery(queryNetworkIdSql, poolname, createdId);
        if (rs.next()) {
            networkId = Util.null2String(rs.getString("field15"));
        }
        logger_52c94c32.info(String.valueOf("RequestId:" + requestId + "Applicant Network ID:" + networkId + ",Query SQL:" + queryNetworkIdSql));
        String createPoStatus = SUCCESS;
        // 主表
        String mainTableName = requestInfo.getRequestManager().getBillTableName();
        // 采购明细表
        String purchaseDetailTableName = requestInfo.getDetailTableInfo().getDetailTable(0).getTableDBName();
        // 采购结果表
        String purchaseResultTableName = requestInfo.getDetailTableInfo().getDetailTable(1).getTableDBName();
        logger_52c94c32.info(String.valueOf("RequestId:" + requestId + ",MainTableName:" + mainTableName + ",PurchaseDetailTableName:" + purchaseDetailTableName + ",PurchaseResultTableName:" + purchaseResultTableName));
        // 获取供应商GSS代码
        Map<String, Map<String, String>> dictInfoByType = DictCommonService.getDictInfoByType("purchase");
        Map<String, String> purchaseDictMap = DictCommonService.get(dictInfoByType.get("purchase"));
        // GSS代码
        String supplierGssCode = purchaseDictMap.get("supplier_GSS_code");
        // 房屋物业GL
        String rentPropertyGlAccount = purchaseDictMap.get("rent_property_gl_account");
        List<String> supplierGssCodeList = Arrays.asList(supplierGssCode.split(","));
        List<String> rentPropertyGlAccountList = Arrays.asList(rentPropertyGlAccount.split(","));
        logger_52c94c32.info(String.valueOf("RequestId:" + requestId + ",supplierGssCodeList:" + supplierGssCodeList + ",rentPropertyGlAccountList:" + rentPropertyGlAccountList));
        // 主表SQL
        //String mainTableQuerySql = "select id,sqfgs,lcbh,fgsjc,jhdz,shr,shrlxdh,ycxgysmc,szcs,jd,gj,dh,yhxx,purchasinggroup,bz,fjsc,internalorder,Order_comment,cglx,ywlx from " + mainTableName + " where requestid = ?";
        String mainTableQuerySql = "SELECT "+mainTableName+".id AS id, "+mainTableName+".sqfgs AS sqfgs, "+mainTableName+".lcbh AS lcbh, "+mainTableName+".fgsjc AS fgsjc, "+mainTableName+".jhdz AS jhdz\n" +
                "\t, "+mainTableName+".shr AS shr, "+mainTableName+".shrlxdh AS shrlxdh, "+mainTableName+".ycxgysmc AS ycxgysmc, "+mainTableName+".szcs AS szcs, "+mainTableName+".jd AS jd\n" +
                "\t, "+mainTableName+".gj AS gj, "+mainTableName+".dh AS dh, "+mainTableName+".yhxx AS yhxx, "+mainTableName+".purchasinggroup AS purchasinggroup, "+mainTableName+".bz AS bz\n" +
                "\t, "+mainTableName+".fjsc AS fjsc, internalorder AS internalorder, "+mainTableName+".order_comment AS Order_comment, cglx AS cglx, "+mainTableName+".ywlx AS ywlx\n" +
                "FROM (\n" +
                "\tSELECT b.*, a.requestid\n" +
                "\tFROM e10_core_business.wfc_form_data a, e10_core_business."+mainTableName+" b\n" +
                "\tWHERE a.dataid = b.form_data_id\n" +
                "\t\tAND a.delete_type = 0\n" +
                "\t\tAND a.tenant_key = 'tl2k2r96ty'\n" +
                ") "+mainTableName+"\n" +
                "WHERE "+mainTableName+".requestid = ?\n" +
                "\tAND "+mainTableName+".delete_type = 0\n" +
                "\tAND "+mainTableName+".tenant_key = 'tl2k2r96ty'";
        
        logger_52c94c32.info(String.valueOf("RequestId:" + requestId + ",MainTableQuerySql:" + mainTableQuerySql));
        String poolname_is = CONN_TYPE.workflow.getType();
        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
        rs.executeQuery(mainTableQuerySql, poolname_is, requestId);
        // 主表ID
        String mainId = "";
        // 申请分公司ID
        String branchId = "";
        // 申请分公司
        String branch = "";
        // 流程编号
        String processNo = "";
        // 分公司简称
        String branchAbbreviation = "";
        // 交货地址
        String deliveryAddress = "";
        // 收货人ID
        String consigneeId = "";
        // 收货人
        String consignee = "";
        // 收货人联系电话
        String consigneePhone = "";
        // 一次性供应商名称
        String oneTimeSupplierName = "";
        // 所在城市
        String city = "";
        // 街道
        String street = "";
        // 国家
        String country = "";
        // 电话
        String telephone = "";
        // 银行信息
        String bankInfo = "";
        // 采购组Id
        String purchasingGroupId = "";
        // 采购组
        String purchasingGroup = "";
        // 币种
        String currency = "";
        // 附件ID
        String attachmentId = "";
        String internalOrderMain = "";
        // 订单备注
        String orderNotes = "";
        // 采购类型(0:FAC-房租类,1:TPE-工具装备类,2:Travel,3:AHQ-服务类,4:ICT-IT类,5:固定车辆租赁费)
        String purchaseType = "";
        // 业务类型(0:固定资产类,1:成本类-入KCC,2:成本类-入KCC及order)
        String businessType = "";
        if (rs.next()) {
            mainId = Util.null2String(rs.getString("id"));
            processNo = Util.null2String(rs.getString("lcbh"));
            branchId = Util.null2String(rs.getString("sqfgs"));
            branchAbbreviation = Util.null2String(rs.getString("fgsjc"));
            attachmentId = Util.null2String(rs.getString("fjsc"));
            deliveryAddress = Util.null2String(rs.getString("jhdz"));
            consigneeId = Util.null2String(rs.getString("shr"));
            consigneePhone = Util.null2String(rs.getString("shrlxdh"));
            oneTimeSupplierName = Util.null2String(rs.getString("ycxgysmc"));
            city = Util.null2String(rs.getString("szcs"));
            street = Util.null2String(rs.getString("jd"));
            country = Util.null2String(rs.getString("gj"));
            telephone = Util.null2String(rs.getString("dh"));
            bankInfo = Util.null2String(rs.getString("yhxx"));
            purchasingGroupId = Util.null2String(rs.getString("purchasinggroup"));
            currency = Util.null2String(rs.getString("bz"));
            internalOrderMain = Util.null2String(rs.getString("internalorder"));
            orderNotes = Util.null2String(rs.getString("Order_comment"));
            purchaseType = Util.null2String(rs.getString("cglx"));
            businessType = Util.null2String(rs.getString("ywlx"));
        }
        /**
         * 业务类型(0:固定资产类,1:成本类-入KCC,2:成本类-入KCC及order)
         * 以根据采购流程业务类型来区分，如果为A则固定资产，创建PO时该字段进行赋x值，其他为空
         */
        // String grNonValued = "";
        // if (StringUtils.isNotBlank(businessType)) {
        // if ("0".equals(businessType)) {
        // grNonValued = "x";
        // }
        // }
        // 删除最终采购结果表中本流程的所有结果
        //String deleteHistoryDataSql = "delete from " + purchaseResultTableName + " where mainid = ?";
        String deleteHistoryDataSql = "delete from " + purchaseResultTableName + " where form_data_id = ? AND delete_type = 0 " +
                " AND tenant_key = 'tl2k2r96ty'";
        String poolname_8m = CONN_TYPE.workflow.getType();
        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
        boolean deleteResult = rs.executeUpdate(deleteHistoryDataSql, poolname_8m, mainId);
        logger_52c94c32.info(String.valueOf("deleteResult:" + deleteResult + ",deleteHistoryDataSql:" + deleteHistoryDataSql));
        String errorMessage;
        // 根据供应商代码分组创建PO
        //String groupSupplierSql = "select gysdm from " + purchaseDetailTableName + " where mainid = ? group by gysdm";
        String groupSupplierSql = "select gysdm from " + purchaseDetailTableName + " where form_data_id = ? group by gysdm";
        logger_52c94c32.info(String.valueOf("RequestId:" + requestId + ",groupSupplierSql:" + groupSupplierSql));
        String poolname_9d = CONN_TYPE.workflow.getType();
        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
        rs.executeQuery(groupSupplierSql, poolname_9d, mainId);
        RecordSet rs2 = I18nContextUtil.getBean(RecordSet.class);
        // 遍历供应商，创建PO
        while (rs.next()) {
            RecordSet purchaseDtlRS = I18nContextUtil.getBean(RecordSet.class);
            // 供应商代码
            String currentSupplierCode = Util.null2String(rs.getString("gysdm"));
            //String purchaseDtlSql = "select id,msdhh,msdhhao,sl,dw,gdzcbh,glaccount,accountassignment,cbzxbh,cgcbj,storagelocation,bl,wlhz,itemmaterialtext,delivery_date from " + purchaseDetailTableName + " where mainid = ? and gysdm = ?";
            String purchaseDtlSql = "select id,msdhh,msdhhao,sl,dw,gdzcbh,glaccount,accountassignment,cbzxbh,cgcbj,storagelocation,bl,wlhz,itemmaterialtext,delivery_date from " + purchaseDetailTableName + " where form_data_id = ? and gysdm = ?";
            logger_52c94c32.info(String.valueOf("RequestId:" + requestId + ",SupplierCode:" + currentSupplierCode + ",PurchaseDtlSql:" + purchaseDtlSql));
            String poolname_5j = CONN_TYPE.workflow.getType();
            // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
            purchaseDtlRS.executeQuery(purchaseDtlSql, poolname_5j, mainId, currentSupplierCode);
            // 序号:初始值为0，每行递增10（例如：10，20,30）
            long detailId = 0L;
            // 描述/订货号
            String describeOrOrderNo = "";
            // 由物料号自动带出
            String describeOrOrderNoAuto = "";
            // 手动填写
            String describeOrOrderNoManual = "";
            // 数量
            double quantity;
            // 单位
            String unit = "";
            // G/L Account
            String glAccount = "";
            // Account Assignment
            String accountAssignment = "";
            // 采购成本价（含税价）
            String grossPrice = "";
            // storage location
            String storageLocation = "";
            // 成本中心编号
            String costCenterNo = "";
            // 固定资产编号
            String fixedAssetNo = "";
            // 发票税率
            String invoiceTaxRate;
            // 物料号
            String material = "";
            // 创建PO唯一标识，用于SAP防止重复创建PO
            String extProcessID = "BPM_" + requestId + "_" + currentSupplierCode;
            // 交货日期
            String deliveryDate;
            PoHeader poHeader = new PoHeader();
            poHeader.setVendor(currentSupplierCode);
            if (StringUtils.isNotBlank(networkId)) {
                poHeader.setCreatedBy(networkId);
            }
            /**
             * 描述：
             * 为了后续订单能够正确GRIR，BPM PR转PO中，除了房租物业和GSS订单外，其他所有PO生成后需要勾选SAP参数：GR-Bsd IV
             * 1，供应商为GSS，PR-PO的时候，不勾选SAP参数：GR-Bsd IV
             * 2，费用为房租物业类型，PR-PO的时候，不勾选SAP参数：GR-Bsd IV，建议可抓取房租物业的GL：436500&436980
             * 3，其余订单，PR-PO的时候，勾选SAP参数：GR-Bsd IV
             * 不打勾为空，打勾赋值x
             */
            String grBasedIV = "x";
            if ((StringUtils.isNotBlank(glAccount) && rentPropertyGlAccountList.contains(glAccount)) || supplierGssCodeList.contains(currentSupplierCode)) {
                grBasedIV = "";
            }
            // 采购组ID转换
            RecordSet purchaseRS = I18nContextUtil.getBean(RecordSet.class);
            //String purchasingGroupSql = "select id,purchasinggroup from uf_pcgroup where id = ?";
            String purchasingGroupSql = "SELECT uf_pcgroup.id AS id, uf_pcgroup.purchasinggroup AS purchasinggroup\n" +
                    "FROM e10_common.uf_pcgroup " +
                    "WHERE uf_pcgroup.id = ? " +
                    "\tAND uf_pcgroup.delete_type = 0 " +
                    "\tAND uf_pcgroup.tenant_key = 'tl2k2r96ty'";
            logger_52c94c32.info(String.valueOf("RequestId:" + requestId + ",SupplierCode:" + currentSupplierCode + ",PurchasingGroupSql:" + purchasingGroupSql));
            String poolname_qa = CONN_TYPE.workflow.getType();
            // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
            purchaseRS.executeQuery(purchasingGroupSql, poolname_qa, purchasingGroupId);
            if (purchaseRS.next()) {
                purchasingGroup = Util.null2String(purchaseRS.getString("purchasinggroup"));
            }
            poHeader.setPurchaseGroup(purchasingGroup);
            poHeader.setPurchaseOrg("KCCA");
            // 获取币种名字
            String sql ="select currency_name from e10-base.i18n_currency  where id=?";
            rs2.executeQuery(sql,CONN_TYPE.workflow,currency);
            String currency_name ="";
            if(rs2.next()){
                currency_name = rs2.getString("currency_name");
            }
           // poHeader.setCurrency(Currency.fromType(currency).getName());
            poHeader.setCurrency(currency_name);
            poHeader.setExtProcessID(extProcessID);
            List<PoItemAddress> poItemAddressList = new ArrayList<>();
            // 申请分公司ID转换
            RecordSet branchRS = I18nContextUtil.getBean(RecordSet.class);
            //String branchSql = "select id,departmentname from hrmdepartment where id = ?";
            String branchSql = "SELECT hrmdepartment.id AS id, hrmdepartment.fullname AS departmentname\n" +
                    "FROM eteams.department hrmdepartment\n" +
                    "WHERE hrmdepartment.id = ?\n" +
                    "\tAND hrmdepartment.type = 'department'\n" +
                    "\tAND hrmdepartment.virtualid = 1\n" +
                    "\tAND hrmdepartment.delete_type = 0\n" +
                    "\tAND hrmdepartment.tenant_key = 'tl2k2r96ty'";
            logger_52c94c32.info(String.valueOf("RequestId:" + requestId + ",SupplierCode:" + currentSupplierCode + ",BranchSql:" + branchSql));
            String poolname_6n = CONN_TYPE.workflow.getType();
            // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
            branchRS.executeQuery(branchSql, poolname_6n, branchId);
            if (branchRS.next()) {
                branch = Util.null2String(branchRS.getString("departmentname"));
            }
            // 根据收货人ID查询收货人lastname
            if (StringUtils.isNotBlank(consigneeId)) {
                List<HrmResourceInfo> hrmResourceInfoList = new ArrayList<>();
                HrmResourceInfo hrmResourceInfo = new HrmResourceInfo();
                hrmResourceInfo.setId(Long.parseLong(consigneeId));
                hrmResourceInfoList.add(hrmResourceInfo);
                List<HrmResourceInfo> resultList = PlatformCommonService.getUsersInfoBatch(hrmResourceInfoList);
                if (!resultList.isEmpty()) {
                    consignee = resultList.get(0).getLastName();
                }
            }
            PoItemAddress poItemAddress = new PoItemAddress();
            poItemAddress.setName(branch);
            // GSS供应商增加传联系人信息到name4
            if (supplierGssCodeList.contains(currentSupplierCode)) {
                poItemAddress.setName4(consignee + "：" + consigneePhone);
                poItemAddress.setStreet(deliveryAddress);
            } else {
                poItemAddress.setName3("联系人：" + consignee);
                poItemAddress.setStreet("交货地址：" + deliveryAddress);
                poItemAddress.setTelephone("联系电话：" + consigneePhone);
            }
            poItemAddress.setCity(city);
            poItemAddressList.add(poItemAddress);
            PoAddress poAddress = null;
            List<PoHeaderText> poHeaderTextList = new ArrayList<>();
            PoHeaderText poHeaderText = new PoHeaderText();
            poHeaderText.setTextID("F01");
            poHeaderText.setTextLine(orderNotes);
            poHeaderTextList.add(poHeaderText);
            // 如果vendor为KONEOTV,报文才送poAddress和poHeaderTexts
            if (currentSupplierCode.equals("KONEOTV")) {
                poAddress = new PoAddress();
                poAddress.setName(oneTimeSupplierName);
                poAddress.setCity(city);
                poAddress.setStreet(street);
                poAddress.setCountry(country);
                poAddress.setTelephone(telephone);
                String[] bankInfoArray = bankInfo.split(";");
                for (String item : bankInfoArray) {
                    if (StringUtils.isNotBlank(item)) {
                        poHeaderText = new PoHeaderText();
                        poHeaderText.setTextID("F01");
                        poHeaderText.setTextLine(item);
                        poHeaderTextList.add(poHeaderText);
                    }
                }
            }
            // 将收货人、收货人联系方式、交货地址三个字段传到header text的delivery处
            if (StringUtils.isNotBlank(consignee)) {
                poHeaderText = new PoHeaderText();
                poHeaderText.setTextID("F14");
                poHeaderText.setTextLine("联系人：" + consignee);
                poHeaderTextList.add(poHeaderText);
            }
            if (StringUtils.isNotBlank(consigneePhone)) {
                poHeaderText = new PoHeaderText();
                poHeaderText.setTextID("F14");
                poHeaderText.setTextLine("联系电话：" + consigneePhone);
                poHeaderTextList.add(poHeaderText);
            }
            if (StringUtils.isNotBlank(deliveryAddress)) {
                poHeaderText = new PoHeaderText();
                poHeaderText.setTextID("F14");
                poHeaderText.setTextLine("交货地址：" + deliveryAddress);
                poHeaderTextList.add(poHeaderText);
            }
            List<PoItem> poItemList = new ArrayList<>();
            List<PoAccount> poAccountList = new ArrayList<>();
            List<PoCondition> poConditionList = new ArrayList<>();
            logger_52c94c32.info(String.valueOf("RequestId:" + requestId + ",SupplierCode:" + currentSupplierCode + "======According To Supplier Details Create PO Start======SupplierCode:" + currentSupplierCode));
            // 遍历供应商明细信息，拼报文
            while (purchaseDtlRS.next()) {
                detailId += 10;
                quantity = purchaseDtlRS.getDouble("sl");
                unit = Util.null2String(purchaseDtlRS.getString("dw"));
                accountAssignment = Util.null2String(purchaseDtlRS.getString("accountassignment"));
                invoiceTaxRate = purchaseDtlRS.getString("bl");
                glAccount = Util.null2String(purchaseDtlRS.getString("glaccount"));
                grossPrice = Util.null2String(purchaseDtlRS.getString("cgcbj"));
                describeOrOrderNoAuto = Util.null2String(purchaseDtlRS.getString("msdhh"));
                describeOrOrderNoManual = Util.null2String(purchaseDtlRS.getString("msdhhao"));
                // describeOrOrderNoManual存在以手动填写为准，否则以物料号自动带出描述为准
                describeOrOrderNo = StringUtils.isNotBlank(describeOrOrderNoManual) ? describeOrOrderNoManual : describeOrOrderNoAuto;
                storageLocation = Util.null2String(purchaseDtlRS.getString("storagelocation"));
                costCenterNo = Util.null2String(purchaseDtlRS.getString("cbzxbh"));
                fixedAssetNo = Util.null2String(purchaseDtlRS.getString("gdzcbh"));
                material = Util.null2String(purchaseDtlRS.getString("wlhz"));
                deliveryDate = Util.null2String(purchaseDtlRS.getString("delivery_date"));
                PoItem poItem = new PoItem();
                PoAccount poAccount = new PoAccount();
                PoCondition poCondition = new PoCondition();
                poItem.setItemNumber(String.valueOf((int) detailId));
                poItem.setStorageLocation(storageLocation);
                int processNoLength = processNo.length();
                // 截取后7位流程编号
                if (processNoLength >= 7) {
                    String versionNo = processNo.substring(4, 5);
                    String processNoSuffix = processNo.substring(processNoLength - 7);
                    poItem.setRequirementTrackingNr(versionNo + branchAbbreviation + processNoSuffix);
                }
                poItem.setAcctAssCat(accountAssignment);
                poItem.setMaterial(material);
                poItem.setPlant("KCC");
                poItem.setShortText(describeOrOrderNo);
                // 如果物料号为空时默认为A，否则为空
                if (StringUtils.isBlank(material)) {
                    poItem.setMaterialGroup("A");
                }
                // commercial
                poItem.setQuantity(quantity);
                // 单位转换
                RecordSet unitRS = I18nContextUtil.getBean(RecordSet.class);
                //String unitSql = "select unit from uf_dwzhb where commercial = ?";
                String unitSql = "SELECT uf_dwzhb.unit AS unit\n" +
                        "FROM e10_common.uf_dwzhb\n" +
                        "WHERE uf_dwzhb.commercial = ?\n" +
                        "\tAND uf_dwzhb.delete_type = 0\n" +
                        "\tAND uf_dwzhb.tenant_key = 'tl2k2r96ty'";
                logger_52c94c32.info(String.valueOf("RequestId:" + requestId + ",SupplierCode:" + currentSupplierCode + ",UnitSql:" + unitSql));
                String poolname_ue = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                unitRS.executeQuery(unitSql, poolname_ue, unit);
                if (unitRS.next()) {
                    unit = Util.null2String(unitRS.getString("unit"));
                }
                poItem.setUnit(unit);
                poItem.setPriceUnit(unit);
                // poItem.setGrNonValuated(grNonValued);
                poItem.setGrBasedIV(grBasedIV);
                if (StringUtils.isNotBlank(grossPrice)) {
                    try {
                        poItem.setGrossPrice(new DecimalFormat().parse(grossPrice).doubleValue());
                    } catch (ParseException e) {
                        logger_52c94c32.error(e.getMessage());
                        throw new RuntimeException(e);
                    }
                }
                if (StringUtils.isNotBlank(deliveryDate)) {
                    List<ScheduleLine> scheduleLineList = new ArrayList<>();
                    ScheduleLine scheduleLine = new ScheduleLine();
                    scheduleLine.setDeliveryDate(deliveryDate);
                    scheduleLine.setQuantity(quantity);
                    scheduleLineList.add(scheduleLine);
                    poItem.setScheduleLines(scheduleLineList);
                }
                poAccount.setItemNumber(String.valueOf((int) detailId));
                poAccount.setGlAccount(glAccount);
                switch(accountAssignment) {
                    case "K":
                        poAccount.setCostCenter(costCenterNo);
                        break;
                    case "A":
                        poAccount.setAssetNumber(fixedAssetNo);
                        break;
                    case "X":
                        poAccount.setCostCenter(costCenterNo);
                        poAccount.setInternalOrder(internalOrderMain);
                        break;
                    default:
                        break;
                }
                poCondition.setItemNumber(String.valueOf((int) detailId));
                if (StringUtils.isNotBlank(invoiceTaxRate)) {
                    try {
                        poCondition.setCondValue(new DecimalFormat().parse(invoiceTaxRate).doubleValue());
                    } catch (ParseException e) {
                        logger_52c94c32.error(e.getMessage());
                        throw new RuntimeException(e);
                    }
                }
                poItemList.add(poItem);
                poAccountList.add(poAccount);
                poConditionList.add(poCondition);
            }
            // 构造请求报文
            JsonMessageBuild jsonMessageBuild = new JsonMessageBuild();
            PoReqMessage poReqMessage = jsonMessageBuild.buildPoRequestMessage(poHeader, poAddress, poHeaderTextList, poItemList, null, poItemAddressList, poAccountList, poConditionList);
            // 调用创建PO接口
            Map<String, String> resultMap = sapCommonService.createPurchaseOrder(requestId, poReqMessage, createPoStatus, currentSupplierCode);
            errorMessage = resultMap.get("errorMessage");
            createPoStatus = resultMap.get("createPoStatus");
            String purchaseOrder = resultMap.get("purchaseOrder");
            RecordSet purchaseResultRS = I18nContextUtil.getBean(RecordSet.class);
            // 将创建Po和上传附件结果记录到采购结果表中
            //String insertPurchaseResultSql = "insert into " + purchaseResultTableName + "(mainid,poh,gysdm,fhxx) values(?,?,?,?)";
            String insertPurchaseResultSql = "insert into " + purchaseResultTableName + "(id,form_data_id,poh,gysdm,fhxx,delete_type,tenant_key) values(?,?,?,?,?,?,?)";
            String poolname_et = CONN_TYPE.workflow.getType();
            // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
            boolean insertResult = purchaseResultRS.executeUpdate(insertPurchaseResultSql, poolname_et, IdGenerator.generate(),mainId, purchaseOrder, currentSupplierCode, errorMessage,"0","tl2k2r96ty");
            logger_52c94c32.info(String.valueOf("RequestId:" + requestId + ",SupplierCode:" + currentSupplierCode + ",Insert " + purchaseResultTableName + " Table Status:" + insertResult));
            // 创建PO完成，开始上传附件
            if (StringUtils.isNotBlank(purchaseOrder)) {
                // 如果附件ID存在，上传PO附件；不存在上传附件结果直接赋值success
                if (StringUtils.isNotBlank(attachmentId)) {
                    errorMessage = sapCommonService.uploadAttachments(requestId, purchaseOrder, attachmentId);
                    if (!errorMessage.equals("success")) {
                        createPoStatus = FAILURE_AND_CONTINUE;
                    }
                } else {
                    logger_52c94c32.info(String.valueOf("RequestId:" + requestId + ",SupplierCode:" + currentSupplierCode + ",No Attachments Uploaded,Return Success"));
                    errorMessage = "success";
                }
                // 将上传附件的结果更新到采购结果表中
                logger_52c94c32.info(String.valueOf("RequestId:" + requestId + ",SupplierCode:" + currentSupplierCode + ",Record The Uploading Attachments Result In The Purchase Result Table"));
                RecordSet updateUploadResultRS = I18nContextUtil.getBean(RecordSet.class);
                //String updateSql = "update " + purchaseResultTableName + " set fhxx = ? where mainid = ? and gysdm = ? and poh = ?";
                String updateSql = "update " + purchaseResultTableName + " set fhxx = ? where form_data_id = ? and gysdm = ? and poh = ? AND delete_type = 0";
                String poolname_kj = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean updateResult = updateUploadResultRS.executeUpdate(updateSql, poolname_kj, errorMessage, mainId, currentSupplierCode, purchaseOrder);
                logger_52c94c32.info(String.valueOf("RequestId:" + requestId + ",PurchaseOrder:" + purchaseOrder + ",Update " + purchaseResultTableName + " Table Status:" + updateResult));
            } else {
                logger_52c94c32.info(String.valueOf("RequestId:" + requestId + ",SupplierCode:" + currentSupplierCode + ",Create PO Failed, No Longer Uploading Attachments"));
            }
            logger_52c94c32.info(String.valueOf("RequestId:" + requestId + ",SupplierCode:" + currentSupplierCode + "======According To Supplier Details Create PO Complete======SupplierCode:" + currentSupplierCode));
        }
        logger_52c94c32.info(String.valueOf("RequestId:" + requestId + "======Complete Create NPR PO======ReturnResult:" + createPoStatus));
        return WeaResult.success(getResultMapForAction(weaverResultMap, "result", createPoStatus, requestInfo.getRequestManager()));
    }

    Map<String, Object> getResultMapForAction(Map<String, Object> map, String key, Object value, RequestManager requestManager) {
        if (key != null && !key.isEmpty()) {
            map.put(key, value);
        }
        String msgContent = requestManager.getMessagecontent();
        if (msgContent != null && !msgContent.isEmpty()) {
            map.put("msgContent", msgContent);
        }
        String msgId = requestManager.getMessageid();
        if (msgId != null && !msgId.isEmpty()) {
            map.put("msgId", msgId);
        }
        return map;
    }
}
